using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Globalization;


namespace Microsoft.Office.Project.EPMSync.Config.Library
{
    delegate void AddTextDelegate(TextBoxBase textBox, string content);

    public class TextBoxTraceListener : TraceListener
    {
        private TextBoxBase _textBox;

        public TextBoxTraceListener(TextBox textBox)
        {
            this._textBox = textBox;
        }

        private void AddText ( TextBoxBase textBox, string content )
        {
           if (textBox.InvokeRequired)
           {
              AddTextDelegate addTextDelegate = new AddTextDelegate(AddText);
              textBox.FindForm().BeginInvoke(addTextDelegate, new object[] { textBox, content });
           } 
           else
               textBox.AppendText(content);
        }

        private string IndentString(string message)
        {
            return message.PadLeft(this.IndentLevel * this.IndentSize, ' ');
        }

        public override void Write(object o)
        {
            if (o != null)
                Write(o.ToString());
        }

        public override void Write(string message)
        {
            WriteOutput(message, string.Empty, false);
        }

        public override void Write(object o, string category)
        {
            if (o != null)
                Write(o.ToString(), category);
        }

        public override void Write(string message, string category)
        {
            WriteOutput(message, category, false);
        }

        public override void WriteLine(object o)
        {
            if (o != null)
                WriteLine(o.ToString());
        }

        public override void WriteLine(string message)
        {
            WriteOutput(message, string.Empty, true);
        }

        public override void WriteLine(object o, string category)
        {
            if (o != null)
                WriteLine(o.ToString(), category);
        }

        public override void WriteLine(string message, string category)
        {
            WriteOutput(message, category, true);
        }

        private void WriteOutput(string message, string category, bool addNewLine)
        {
            if (_textBox == null)
                return;

            string output = string.Empty;
            string newLine = string.Empty;

            if (addNewLine)
                newLine = Environment.NewLine;

            if (String.IsNullOrEmpty(category))
                output = String.Format(CultureInfo.InvariantCulture, "{0}{1}", message, newLine);
            else
                output = String.Format(CultureInfo.InvariantCulture, "{0}: {1}{2}", category, message, newLine);

            if (this.IndentLevel > 0)
                AddText(_textBox, IndentString(output));
            else
                AddText(_textBox, output);
        }

    }

}
